<?php

namespace App\Dao;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class VipUser extends Model
{
    public $timestamps = false;
    protected $table = 'vip_user';
    protected $fillable = [ 'disk_code', 'over_time','ymd5','view_count'];

    public static function auth($code){
        $over_time = null;
        $now = Carbon::now();
        $l = VipUser::query()->where('disk_code',$code);
        if($l->count() < 1){//没有用户,插入
            $over_time =  $now->addHour(24);
            VipUser::query()->create([
                'disk_code'=> $code,
                'over_time'=> ($over_time),//时差
                'ymd5'=>hash('md5',$code),
                'view_count'=>1
            ]);
            $r = true;
        }else{
            $user = $l->first();
            $over_time = Carbon::parse($user->over_time);
            if($over_time < $now)
                $r = false;
            else
                $r = true;
        }
        return ['success' => $r,'overTime'=> $over_time,'msg'=>''];
    }

    public static function renew($code,$key){
        //没有储存机器码，失败
        $user = VipUser::query()->where('disk_code',$code)->first();
        if($user == null) {
            return false;
        }

        //找不到key，失败
        $k = Keyz::query()->where(['content'=>$key,'used'=>0])->first();
        if($k == null)
            return false;

        //计算新的到期时间
        $newOverTime = null;
        $now = Carbon::now();
        //如果当前已经过期，则从now顺延一个月
        //否则（如果没有过期），则从用户过期时间顺延一个月
        if($user->over_time < $now) {
            $newOverTime = $now->addMonth(1);
        }else{
            $newOverTime = Carbon::parse($user-> over_time)->addMonth(1);
        }

        $r =  VipUser::query()->where('disk_code',$code) ->update(['over_time' => $newOverTime]);
        if($r <= 0)
            return false;
        Keyz::query()->where('content',$key)->update(['used'=>1]);
        return true;
    }

    //验证用户并且增加观看次数
    public static function validate($md5){
        $user =  VipUser::query()->where('ymd5',$md5)->first();
        if($user == null)
            return false;
        $new_count = 0;
        if($user->view_count != null || $user->view_count == 0)
            $new_count = $user->view_count + 1;
        VipUser::query()->where('ymd5',$md5)->update(['view_count'=>$new_count]);
        return true;
    }
}
